package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 文件上传
     * @param multipartFile 前端穿过来的多个文件:图片
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile)  {
        //1.校验参数
        if (null==multipartFile||multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);//返回缺少参数
        }
        //要上传到minio,我们需要自定义一个文件名称,因为同一天可能会上传同一张图片,所以我们是有UUID来生成文件名再拼上后缀
            String name = UUID.randomUUID().toString().replace("-", "");;
            String filename = multipartFile.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
        String path=null;
        try {
            path = fileStorageService.uploadImgFile("", name + suffix, multipartFile.getInputStream());//上传图片
            log.info("图片的id为:{}",path);
        } catch (IOException e) {
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);//素材引用失败
        }
        //将用户的id和图片上传到素材表中
        //封装一个wmMaterial对象,将数据放进对象中,存入数据库表里
        WmMaterial wmMaterial = new WmMaterial();
        WmUser user = WmThreadLocalUtil.getUser();
        Integer userid = user.getId();
        wmMaterial.setUserId(userid);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short) 0);//上传的是什么类型 0是图片,1是视频
        wmMaterial.setUrl(path);
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
        //        //1.校验前端传来的数据有没有空值
//        if (null==multipartFile||multipartFile.getSize()==0){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }
//        //2.将文件上传到minio
//        String originalFilename = multipartFile.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //因为名称可能会重复,所以使用UUID生成名称
//        String name = UUID.randomUUID().toString();
//        //上传到minio
//        String path=null;
//        try {
//            path = fileStorageService.uploadImgFile("", name + substring, multipartFile.getInputStream());
//        } catch (IOException e) {
//            log.error("上传图片失败");
//            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);//素材引用失败
//
//        }
//        //3.手动封装数据
//        WmMaterial wmMaterial = new WmMaterial();
//        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getApUserId());
//        wmMaterial.setCreatedTime(new Date());
//        wmMaterial.setUrl(path);
//        wmMaterial.setIsCollection((short) 0);
//        wmMaterial.setType((short) 0);
//        //4.保存到素材表
//        this.save(wmMaterial);
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);//上传图片不需要返回值
    }

    /**
     * 查询所有的素材
     * @param wmMaterialDto 前端传来的参数,有page,size,以及checkParam方法
     * @return
     */
    @Override
    public ResponseResult FindAll(WmMaterialDto wmMaterialDto) {
        //校验参数
        wmMaterialDto.checkParam();
        Page<WmMaterial> wmMaterialPage = new Page<>(wmMaterialDto.getPage(),wmMaterialDto.getSize());//创建分页对象
        //创建查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //判断参数里面的是否收藏,因为前面的page和size使用checkParam校验了,所以现在只用校验是否收藏
        if(wmMaterialDto.getIsCollection()!=null){//没有收藏
            wrapper.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        wrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());//按照用户的收藏来查询
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        this.page(wmMaterialPage, wrapper);
        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) wmMaterialPage.getTotal());
        responseResult.setData(wmMaterialPage.getRecords());
        return responseResult;
    }
@Autowired
private WmNewsMapper wmNewsMapper;

    /**
     * 删除素材,如果有被引用就不能删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteimg(Integer id) {
        //图片被引用查询文章表
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getArticleId, id));
        if (null!=wmNews){
            return ResponseResult.errorResult(AppHttpCodeEnum.MATERIAL_ISALRADY_USE);
        }
        //删除minio中的数据
        WmMaterial wmMaterial = this.getById(id);
        String path = wmMaterial.getUrl();
        fileStorageService.delete(path);
        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        WmMaterial material = getById(id);
        Short isCollection = material.getIsCollection();
        if (material.getIsCollection()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        material.setIsCollection((short) 1);
        updateById(material);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelcollect(Integer id) {
        WmMaterial material = getById(id);
        if (material.getIsCollection()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        material.setIsCollection((short) 0);
        updateById(material);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
